﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Reflection;

namespace BestClient
{
    public class FC1000BestImplementation : BestDataProcessor {

    private const string TAG = "BESTImplementation";
    private const string CONFIG_PATH = "sdcard/config/config.yml";
    private const string PERSONS = "persons";
    private const string CODE_LIST = "codeList";
    private const string NAME = "name";
    private const string CODE = "code";
    private const string IS_NEW = "isNew";
    private const string PARAMS = "params";
    private const string ACC_AUTH = "accAuth";
    private const string YES = "Y";
    private const string BIRTHDAY = "birthday";
    private const string GENDER = "gender";
    private const string RECOGNITION = "recognition";
    private const string TARGET = "target";
    private const string START_TIME = "startTime";
    private const string END_TIME = "endTime";
    const string EVENT = "event";
    const string TIMESTAMP = "timestamp";
    const string COUNT = "count";
    const string GROUP_ID = "groupId";
    const string FACE_PHOTO = "facePhoto";
    const string CAPTURE_TIME = "captureTime";
    const string EVENT_CONTENT = "eventContent";
    const string CONDITION = "condition";
    const string ALARM_TIME = "alarmTime";
    const string PID = "pid";
    const string RECOGNITION_TIME = "recognitionTime";
    const string PHOTO = "photo";
    const string COUNT_TIME = "countTime";

    private const string DATABASE_ID = "fc1000_test";

    private const string formatter = "yyyy-MM-dd HH:mm:ss";

        
        
    private Dictionary<string, MethodInfo> SID_MAPPER = new Dictionary<string, MethodInfo>();
    //private static const Set<ORM> ORM_SET = new HashSet<ORM>();
    //private static const Set<string> TABLE_FILTER = new HashSet<string>();

    private const string START_LAUNCHER_ACTION = "com.zkteco.android.fc1000.zklauncher";
    private const string START_LAUNCHER_PACKAGE = "com.zkteco.android.fc1000.zklauncher";
    private const string START_LAUNCHER_ACTIVITY = "com.zkteco.android.fc1000.zklauncher.verify.CameraActivity";

    //static {
    //    ORM_SET.add(new AccessControl());
    //    ORM_SET.add(new CountingLog());
    //    ORM_SET.add(new DetectedFaceLog());
    //    ORM_SET.add(new FaceArea());
    //    ORM_SET.add(new FaceRecognitionLog());
    //    ORM_SET.add(new Group());
    //    ORM_SET.add(new MotionDetectionLog());
    //    ORM_SET.add(new Person());
    //    ORM_SET.add(new PersonBiometric());
    //    ORM_SET.add(new PersonExtra());
    //    //Table filter
    //    TABLE_FILTER.add(CountingLog.TABLE_NAME);
    //    TABLE_FILTER.add(FaceRecognitionLog.TABLE_NAME);
    //    TABLE_FILTER.add(MotionDetectionLog.TABLE_NAME);
    //    TABLE_FILTER.add(DetectedFaceLog.TABLE_NAME);
    //}

    private Context context;
    private BestDataCallBack bestDataCallBack;
    private SettingsProvider settingInstance;
    private OutputProvider outputProvider;

    public FC1000BestImplementation(Context context, BestDataCallBack bestDataCallBack) {
        this.context = context;
        this.bestDataCallBack = bestDataCallBack;
        this.settingInstance = SettingsProvider.getInstance();
        this.outputProvider = new OutputProvider();
        loadMethods();
        initializeDbConnection();
        int flag = settingInstance.get("TABLE_CREATE", 0);
        //Log.i(TAG, "TABLE_CREATE flag:" + flag);
        if (flag == 0) {
            //DataManager.createDatabase(context);
            //DataManager.createGroup();
            settingInstance.set("TABLE_CREATE", 1);
        }
        registerReceiver();
        startLauncher();
        
    }

    private void startLauncher() {
        //const PackageManager packageManager = context.getPackageManager();
        //List<PackageInfo> packageInformation = packageManager.getInstalledPackages(0);
        //List<string> packageNames = new ArrayList<>();
        //if (packageInformation != null) {
        //    for (int i = 0; i < packageInformation.size(); i++) {
        //        string packName = packageInformation.get(i).packageName;
        //        packageNames.add(packName);
        //    }
        //    if (packageNames.contains(START_LAUNCHER_PACKAGE)) {
        //        Intent intent = new Intent(Intent.ACTION_MAIN);
        //        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        //        ComponentName componentName = new ComponentName(START_LAUNCHER_PACKAGE, START_LAUNCHER_ACTIVITY);
        //        intent.setComponent(componentName);
        //        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
        //                | Intent.FLAG_ACTIVITY_NEW_TASK
        //                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        //        context.startActivity(intent);
        //        Log.i(TAG, "Start the launcher");
        //    }

        //}
    }

    private void loadMethods() {
        MethodInfo[] methods = this.GetType().GetMethods();
        foreach (MethodInfo method in methods)
        {
            BestAPI annotation = method.GetCustomAttribute<BestAPI>();
            if (annotation != null) {
                SID_MAPPER.Add(annotation.serviceId, method);                
            }
        }
    }

    private void initializeDbConnection() {
        //ConnectionSource connectionSource = new SQLiteInterfaceConnectionSource(CoreProvider.getInstance(context), DATABASE_ID, 1);
        //try {
        //    ORM.addSource(DATABASE_ID, connectionSource);
        //} catch (SQLException e) {
        //    Log.e(TAG, Log.getStackTracestring(e));
        //}
    }

    private void registerReceiver() {
        //DatabaseChangesProcessor dbReceiver =
        //        new DatabaseChangesProcessor(context, bestDataCallBack, settingInstance, DATABASE_ID);
        //dbReceiver.setTableFilter(TABLE_FILTER);
        //dbReceiver.register(context, DATABASE_ID);
    }

    //@Override
    public string processBestData(BestData bestData) {
        MethodInfo method = null;
        if (SID_MAPPER.ContainsKey(bestData.sid))
        {
            method = SID_MAPPER[bestData.sid];
        }
        string jsonResponse = null;
        if (method != null) {
            try {     
                jsonResponse = (string) method.Invoke(this, new object[]{(object)bestData});
            } catch (Exception e) {
                throw e;
            }
        }
        return jsonResponse;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_PERSON_SYNCHRONIZE)]
    public string createPerson(BestData bestData){
        return string.Empty;
        /*
        List<string> userList = (List<string>) bestData.getPayloadResultKey(PERSONS);
        foreach (string userStr in userList) {
            Dictionary<string, object> userMap = MessageConverter.fromJson(userStr, Map.class);
            string personCode = (string) userMap.get(CODE);
            string isNew = (string) userMap.get(IS_NEW);
            //Daniel.Zhang added on 2017-06-09. test modify person.
            Log.i(TAG,"DZ, is new person: " + isNew);
            if (personCode != null) {
                long peopleCount = new Person().countOf(DATABASE_ID);
                Log.i(TAG, "createPerson number:" + (peopleCount) + " name:" + userMap.get(NAME) + " personCode:" + personCode);
                Person person = new Person();
                person.setCode(personCode);
                Log.i(TAG, "createPerson: code=" + personCode);
                Log.i(TAG, "createPerson: groupID+" + userMap.get(GROUP_ID));
                Log.i(TAG, "createPerson: birthday+" + userMap.get(BIRTHDAY));
                Log.i(TAG, "createPerson: name+" + userMap.get(NAME));
                person.setName((string) userMap.get(NAME));
                if (isNew.equals("true")) {
                    Log.i(TAG,"DZ, start to create person.");
                    person.create(DATABASE_ID);
                    Log.i(TAG,"DZ, end to create person.");
                } else if (isNew.equals("false")) {
                    Log.i(TAG,"DZ, start to update person.");
                    Person personOld = Person.getPerson(DATABASE_ID, personCode);
                    personOld.getDao(DATABASE_ID).update(person);
                    Log.i(TAG,"DZ, end to update person.");
                }
                Group group = new Group().queryForId(DATABASE_ID, Integer.parseInt((string) userMap.get(GROUP_ID)));
                if (group != null) {
                    PersonGroup personGroup = new PersonGroup();
                    personGroup.setGroup(group);
                    personGroup.setPerson(person);
                    if (isNew.equals("true")) {
                        Log.i(TAG,"DZ, start to create personGroup.");
                        personGroup.create(DATABASE_ID);
                        Log.i(TAG,"DZ, end to create personGroup.");
                    } else if (isNew.equals("false")) {
                        Log.i(TAG,"DZ, start to update personGroup.");
                        PersonGroup personGroupOld = new PersonGroup().queryForId(DATABASE_ID, person.getId());
                        personGroupOld.getDao(DATABASE_ID).update(personGroupOld);
                        Log.i(TAG,"DZ, end to update personGroup.");
                    }
                }
                AccessControl accessControl = new AccessControl();
                accessControl.setPersonId(person);
                accessControl.setCode(personCode);
                accessControl.setActivateRelay(userMap.get(ACC_AUTH).equals(YES));
                if (isNew.equals("true")) {
                    Log.i(TAG,"DZ, start to create accessControl.");
                    accessControl.create(DATABASE_ID);
                    Log.i(TAG,"DZ, end to create accessControl.");
                } else if (isNew.equals("false")) {
                    Log.i(TAG,"DZ, start to update accessControl.");
                    AccessControl accessControlOld = new AccessControl().queryForId(DATABASE_ID, person.getId());
                    accessControlOld.getDao(DATABASE_ID).update(accessControl);
                    Log.i(TAG,"DZ, start to update accessControl.");
                }

                PersonBiometric personBiometric = new PersonBiometric();
                personBiometric.setPerson(person);
                personBiometric.setCode(personCode);
                personBiometric.setTemplate((string) userMap.get(PHOTO));
                personBiometric.setName((string) userMap.get(NAME));
                if (isNew.equals("true")) {
                    Log.i(TAG,"DZ, start to create personBiometric");
                    personBiometric.create(DATABASE_ID);
                    Log.i(TAG,"DZ, end to create personBiometric");
                } else if (isNew.equals("false")) {
                    Log.i(TAG,"DZ, start to update personBiometric");
                    PersonBiometric personBiometricOld = new PersonBiometric().queryForId(DATABASE_ID, person.getId());
                    personBiometricOld.getDao(DATABASE_ID).update(personBiometric);
                    Log.i(TAG,"DZ, end to update personBiometric");
                }
                Log.i(TAG, "PersonBiometric info :" + personBiometric.tostring());

                // Through the radio transmission template data
                Intent intent = new Intent();
                intent.setAction(BiometricReceiver.ACTION_ON_ADD_PEOPLE_BIOMETRIC);
                intent.putExtra(BiometricReceiver.PEOPLE_CODE, personBiometric.getCode());
                intent.putExtra(BiometricReceiver.PEOPLE_BIOMETRIC, personBiometric.getTemplate());
                intent.putExtra(BiometricReceiver.PEOPLE_BIOMETRIC_NAME, personBiometric.getName());
                context.sendBroadcast(intent);

                PersonExtra personExtra = new PersonExtra();
                personExtra.setName((string) userMap.get(NAME));
                personExtra.setGender((string) userMap.get(GENDER));
                personExtra.setPhoto((string) userMap.get(PHOTO));
                personExtra.setCode((string) userMap.get(CODE));
                string birthday = (string) userMap.get(BIRTHDAY);
                if (checkNullOrEmpty(birthday)) {
                    try {
                        personExtra.setBirthday(formatter.parse((string) userMap.get(BIRTHDAY)));
                    } catch (ParseException e) {
                        Log.e(TAG, Log.getStackTracestring(e));
                    }
                }
                personExtra.setPerson(person);
                if (isNew.equals("true")) {
                    Log.i(TAG,"DZ, start to create personExtra");
                    personExtra.create(DATABASE_ID);
                    Log.i(TAG,"DZ, end to create personExtra");
                } else if (isNew.equals("false")) {
                    Log.i(TAG,"DZ, start to update personExtra");
                    PersonExtra personExtraOld = new PersonExtra().queryForId(DATABASE_ID, person.getId());
                    personExtraOld.getDao(DATABASE_ID).update(personExtra);
                    Log.i(TAG,"DZ, end to update personExtra");
                }
            }
        }

        return null;
         * */
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_SET_GROUP)]
    public string createGroup(BestData bestData)
    {
        List<Dictionary<string, object>> paramList = (List<Dictionary<string, object>>) bestData.getPayloadParamList();
        string jsonResult;
        try {
            foreach (Dictionary<string, object> paramMap in paramList) {
                //Log.i(TAG, "createGroup:= " + paramMap.get(GROUP_ID));
                //Group group = new Group();
                //group.setId(Integer.parseInt((string) paramMap.get(GROUP_ID)));
                //group.setName((string) paramMap.get(NAME));
                //group.create(DATABASE_ID);
            }
            jsonResult = MessageConverter.uploadReceiveResult(context,
                    BestConstant.SERVICE_ID_COMMAND_SET_GROUP, BestConstant.CODE_OK);
        } catch (Exception e) {
            //Log.e(TAG, Log.getStackTracestring(e));
            jsonResult = MessageConverter.uploadReceiveResult(context,
                    BestConstant.SERVICE_ID_COMMAND_SET_GROUP, BestConstant.DB_SET_GROUP_FAIL);
        }
        return jsonResult;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_PERSON_DELETE)]
    public string deletePerson(BestData bestData)
    {
        List<string> codeList = (List<string>) bestData.getPayloadParam(CODE_LIST);
        //Log.d(TAG, "deletePerson: =" + codeList.get(0));
        string resultJson = null;
        try {
            //DeleteBuilder<Person, Integer> deleteBuilder = new Person().getDao(DATABASE_ID).deleteBuilder();
            //DeleteBuilder<PersonBiometric, Integer> deleteBuilderByBiometric = new PersonBiometric().getDao(DATABASE_ID).deleteBuilder();
            //DeleteBuilder<PersonExtra, Integer> deleteBuilderByPersonExtra = new PersonExtra().getDao(DATABASE_ID).deleteBuilder();
            //DeleteBuilder<PersonGroup, Integer> deleteBuilderByPersonGroup = new PersonGroup().getDao(DATABASE_ID).deleteBuilder();
            //DeleteBuilder<AccessControl, Integer> deleteBuilderByAccessControl = new AccessControl().getDao(DATABASE_ID).deleteBuilder();

            foreach(string code in codeList) {
                //Person person = Person.getPerson(DATABASE_ID, code);
                if (true) {
                    //Log.i(TAG, "deletePerson ：" + person.tostring());
                    //Removed by broadcasting algorithm the template in memory
                    //Intent intent = new Intent();
                    //intent.setAction(BiometricReceiver.ACTION_ON_DELETE_PEOPLE_BIOMETRIC);
                    //intent.putExtra(BiometricReceiver.PEOPLE_CODE, code);
                    //intent.putExtra(BiometricReceiver.PEOPLE_BIOMETRIC_NAME, person.getName());
                    //context.sendBroadcast(intent);

                    //deleteBuilder.where().eq(CODE, code);
                    //deleteBuilder.delete();
                    //deleteBuilderByBiometric.where().eq(CODE, code);
                    //deleteBuilderByBiometric.delete();

                    //deleteBuilderByPersonExtra.where().eq(CODE, code);
                    //deleteBuilderByPersonExtra.delete();

                    //deleteBuilderByPersonGroup.where().eq(CODE, code);
                    //deleteBuilderByPersonGroup.delete();

                    //deleteBuilderByAccessControl.where().eq(CODE, code);
                    //deleteBuilderByAccessControl.delete();

                    resultJson = MessageConverter.uploadReceiveResult(context,
                            BestConstant.SERVICE_ID_COMMAND_PERSON_DELETE, BestConstant.CODE_OK);
                } else {
                    resultJson = MessageConverter.uploadReceiveResult(context,
                            BestConstant.SERVICE_ID_COMMAND_PERSON_DELETE, BestConstant.DB_DELETE_PERSON_FAIL);
                }
            }
        } catch (Exception e) {
            //Log.e(TAG, Log.getStackTracestring(e));
            resultJson = MessageConverter.uploadReceiveResult(context,
                    BestConstant.SERVICE_ID_COMMAND_PERSON_DELETE, BestConstant.DB_DELETE_PERSON_FAIL);
        }
        return resultJson;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_COUNT_UPLOAD)]
    public string uploadRecord(BestData bestData)
    {
        string target = (string) bestData.getPayload(TARGET);
        Dictionary<string, string> param = (Dictionary<string, string>) bestData.getPayload(PARAMS);
        List<object> paramList = new List<object>();
        string jsonResult = null;
        //Date startTime = formatter.parse(param[START_TIME]);
        //Date endTime = formatter.parse(param.get(END_TIME));
        //if (target.equals(COUNT)) {
        //    for (CountingLog cLog : (List<CountingLog>) getLogsByDate(new CountingLog(), startTime, endTime)) {
        //        Dictionary<string, object> paramMap = new HashDictionary<string, object>();
        //        paramMap.put(COUNT, cLog.getNumber());
        //        Log.i(TAG, "uploadRecord: =" + cLog.getNumber());
        //        paramMap.put(COUNT_TIME, formatter.format(cLog.getTimestamp()));
        //        paramList.add(paramMap);
        //    }
        //    jsonResult = MessageConverter.uploadCountRecord(context, paramList);
        //} else if (target.equals(RECOGNITION)) {
        //    for (FaceRecognitionLog fLog : (List<FaceRecognitionLog>) getLogsByDate(new FaceRecognitionLog(), startTime, endTime)) {
        //        Dictionary<string, object> paramMap = new HashDictionary<string, object>();
        //        paramMap.put(PID, fLog.getPerson().getId());
        //        // Put first groupId
        //        Group group = Person.getPersonGroup(DATABASE_ID, fLog.getPerson().getId());
        //        if (group != null) {
        //            params.put(FC1000BestImplementation.GROUP_ID, string.valueOf(group.getId()));
        //        }
        //        paramMap.put(RECOGNITION_TIME, formatter.format(fLog.getTimestamp()));
        //        paramMap.put(PHOTO, fLog.getPhoto());
        //        paramList.add(paramMap);
        //    }
        //    jsonResult = MessageConverter.uploadRecognitionLog(context, paramList);
        //} else if (target.equals(EVENT)) {
        //    for (MotionDetectionLog mLog : (List<MotionDetectionLog>) getLogsByDate(new MotionDetectionLog(), startTime, endTime)) {
        //        Dictionary<string, object> paramMap = new HashDictionary<string, object>();
        //        paramMap.put(EVENT_CONTENT, mLog.getEventCode());
        //        paramMap.put(CONDITION, mLog.getInformation());
        //        paramMap.put(ALARM_TIME, formatter.format(mLog.getTimestamp()));
        //        paramList.add(paramMap);
        //    }
        //    jsonResult = MessageConverter.uploadAlarmEventLog(context, paramList);
        //} else if (target.equals(PHOTO)) {
        //    for (DetectedFaceLog dLog : (List<DetectedFaceLog>) getLogsByDate(new DetectedFaceLog(), startTime, endTime)) {
        //        Dictionary<string, object> paramMap = new HashDictionary<string, object>();
        //        paramMap.put(FACE_PHOTO, dLog.getImage());
        //        paramMap.put(CAPTURE_TIME, dLog.getTimestamp());
        //        paramList.add(paramMap);
        //    }
        //    jsonResult = MessageConverter.uploadPhoto(context, paramList);
        //}
        return jsonResult;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_UPLOAD_COUNT)]
    public string uploadCountLogSucceed(BestData bestData)
    {
        string timeStamp = (string) settingInstance.get(bestData.mid, null);
        //if (timeStamp != null) {
        //    bool isSucceed = true;
        //    try {
        //        DeleteBuilder<CountingLog, Integer> deleteBuilder = new CountingLog().getDao(DATABASE_ID).deleteBuilder();
        //        deleteBuilder.where().eq(TIMESTAMP, new Date(Long.parseLong(timeStamp)));
        //        deleteBuilder.delete();
        //    } catch (SQLException e) {
        //        isSucceed = false;
        //        Log.e(TAG, Log.getStackTracestring(e));
        //    }
        //    removeLogByMid(bestData.getMid(), isSucceed);
        //}
        return null;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_UPLOAD_RECOGNITION)]
    public string uploadRecognitionLogSucceed(BestData bestData)
    {
        string timeStamp = (string) settingInstance.get(bestData.mid, null);
        //if (timeStamp != null) {
        //    bool isSucceed = true;
        //    try {
        //        DeleteBuilder<FaceRecognitionLog, Integer> deleteBuilder = new FaceRecognitionLog().getDao(DATABASE_ID).deleteBuilder();
        //        deleteBuilder.where().eq(TIMESTAMP, timeStamp);
        //        deleteBuilder.delete();
        //    } catch (SQLException e) {
        //        isSucceed = false;
        //        Log.e(TAG, Log.getStackTracestring(e));
        //    }
        //    removeLogByMid(bestData.getMid(), isSucceed);
        //}
        return null;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_UPLOAD_ALARM_LOG)]
    public string uploadMotionLogSucceed(BestData bestData)
    {
        string timeStamp = (string) settingInstance.get(bestData.mid, null);
        //if (timeStamp != null) {
        //    bool isSucceed = true;
        //    try {
        //        DeleteBuilder<MotionDetectionLog, Integer> deleteBuilder = new MotionDetectionLog().getDao(DATABASE_ID).deleteBuilder();
        //        deleteBuilder.where().eq(TIMESTAMP, new Date(Long.parseLong(timeStamp)));
        //        deleteBuilder.delete();
        //    } catch (Exception e) {
        //        isSucceed = false;
        //        //Log.e(TAG, Log.getStackTracestring(e));
        //    }
        //    removeLogByMid(bestData.mid, isSucceed);
        //}
        return null;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_UPLOAD_PHOTO)]
    public string uploadDetectedFaceLogSucceed(BestData bestData)
    {
        string timeStamp = (string) settingInstance.get(bestData.mid, null);
        if (timeStamp != null) {
            //boolean isSucceed = true;
            //try {
            //    DeleteBuilder<DetectedFaceLog, Integer> deleteBuilder = new DetectedFaceLog().getDao(DATABASE_ID).deleteBuilder();
            //    deleteBuilder.where().eq(TIMESTAMP, new Date(Long.parseLong(timeStamp)));
            //    deleteBuilder.delete();
            //} catch (SQLException e) {
            //    isSucceed = false;
            //    Log.e(TAG, Log.getStackTracestring(e));
            //}
            //removeLogByMid(bestData.getMid(), isSucceed);
        }
        return null;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_REBOOT_DEVICE)]
    public string rebootDeviceCommand(BestData bestData)
    {
        string jsonResult = null;
        //try {
        //    Log.i(TAG, "rebootDeviceCommand: device is rebooting");
        //    Thread.sleep(3000);
        //    outputProvider.reboot(OutputInterface.Output.RST);
        //} catch (Exception e) {
        //    jsonResult = MessageConverter.uploadReceiveResult(context, BestConstant.SERVICE_ID_COMMAND_REBOOT_DEVICE,
        //            BestConstant.REBOOT_DEVICE_FAIL);
        //    Log.e(TAG, Log.getStackTracestring(e));
        //}
        return jsonResult;
    }


    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_RELAY_ON)]
    public string setRelayStatus(BestData bestData)
    {
        string jsonResult = null;
        //try {
        //    Log.i(TAG, "setRelayStatus: relay is set on");
        //    outputProvider.activateOutput(OutputInterface.Output.RELAY, 0L, Long.parseLong((string) settingInstance.get("relay-times", "20")) * 1000);
        //} catch (Exception e) {
        //    jsonResult = MessageConverter.uploadReceiveResult(context, BestConstant.SERVICE_ID_COMMAND_REBOOT_DEVICE,
        //            BestConstant.REBOOT_DEVICE_FAIL);
        //    Log.e(TAG, Log.getStackTracestring(e));
        //}
        return jsonResult;

    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_CLEAR_COUNT)]
    public string deleteAllCount(BestData bestData)
    {
        string resultJson = string.Empty;
        //try {
        //    new CountingLog().clearTable(DATABASE_ID);
        //    resultJson = MessageConverter.uploadReceiveResult(context,
        //            BestConstant.SERVICE_ID_COMMAND_CLEAR_COUNT, BestConstant.CODE_OK);
        //} catch (SQLException e) {
        //    Log.e(TAG, Log.getStackTracestring(e));
        //    resultJson = MessageConverter.uploadReceiveResult(context,
        //            BestConstant.SERVICE_ID_COMMAND_CLEAR_COUNT, BestConstant.DB_CLEAR_COUNT_FAIL);
        //}
        return resultJson;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_CLEAR_RECOGNITION)]
    public string deleteAllRecognition(BestData bestData)
    {
        string resultJson = string.Empty;
        //try {
        //    new FaceRecognitionLog().clearTable(DATABASE_ID);
        //    resultJson = MessageConverter.uploadReceiveResult(context,
        //            BestConstant.SERVICE_ID_COMMAND_CLEAR_RECOGNITION, BestConstant.CODE_OK);
        //} catch (SQLException e) {
        //    Log.e(TAG, Log.getStackTracestring(e));
        //    resultJson = MessageConverter.uploadReceiveResult(context,
        //            BestConstant.SERVICE_ID_COMMAND_CLEAR_RECOGNITION, BestConstant.DB_CLEAR_RECOGNITION_FAIL);
        //}
        return resultJson;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_CLEAR_PHOTO)]
    public string deleteAllPhoto(BestData bestData)
    {
        string resultJson = string.Empty;
        //try {
        //    new DetectedFaceLog().clearTable(DATABASE_ID);
        //    resultJson = MessageConverter.uploadReceiveResult(context,
        //            BestConstant.SERVICE_ID_COMMAND_CLEAR_PHOTO, BestConstant.CODE_OK);
        //} catch (SQLException e) {
        //    Log.e(TAG, Log.getStackTracestring(e));
        //    resultJson = MessageConverter.uploadReceiveResult(context,
        //            BestConstant.SERVICE_ID_COMMAND_CLEAR_PHOTO, BestConstant.DB_CLEAR_PHOTO_FAIL);
        //}
        return resultJson;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_CLEAR_ALL)]
    public string deleteAllData(BestData bestData)
    {
        string jsonResult;
        try {
            deleteAllTables();
            createAllTables();
            jsonResult = MessageConverter.uploadReceiveResult(context,
                    BestConstant.SERVICE_ID_COMMAND_CLEAR_ALL, BestConstant.CODE_OK);
        } catch (Exception e) {
            //Log.e(TAG, Log.getStackTracestring(e));
            jsonResult = MessageConverter.uploadReceiveResult(context,
                    BestConstant.SERVICE_ID_COMMAND_CLEAR_ALL, BestConstant.DB_CLEAR_ALL_FAIL);
        }
        return jsonResult;
    }

    [BestAPI(serviceId = BestConstant.SERVICE_ID_COMMAND_CAMERA_INFORMATION)]
    public string setCameraInfo(BestData bestData)
    {
        string jsonResult = null;
        try {
//            Dictionary<string, string> params = (Dictionary<string, string>) bestData.getPayload(PARAMS);
//            Log.i(TAG, "setCameraInfo: imageSize =  " + params.get("imageSize"));
//            Log.i(TAG, "setCameraInfo: recThreshold =  " + params.get("recThreshold"));
//            Log.i(TAG, "setCameraInfo: eyesDistance =  " + params.get("eyesDistance"));
//            Log.i(TAG, "setCameraInfo: videoMirror =  " + params.get("videoMirror"));
//            Log.i(TAG, "setCameraInfo: relayTime =  " + params.get("relayTime"));
//            settingInstance.set("image-format", params.get("imageSize"));
//            settingInstance.set("min-eyes-distance", params.get("eyesDistance"));
//            settingInstance.set("video-mirror", params.get("videoMirror"));
//            settingInstance.set("verifierFace-threshold", params.get("recThreshold"));
//            settingInstance.set("relay-times", params.get("relayTime"));

//            Log.i(TAG, "setCameraInfo: videoMirror 1 =  " + settingInstance.get("image-format", "图片"));
//            Log.i(TAG, "setCameraInfo: recThreshold 1 =  " + settingInstance.get("verifierFace-threshold", "阈值"));
//            Log.i(TAG, "setCameraInfo: eyesDistance 1 =  " + settingInstance.get("min-eyes-distance", "间距"));
//            Log.i(TAG, "setCameraInfo: imageSize 1 =  " + settingInstance.get("video-mirror", "镜像"));
//            Log.i(TAG, "setCameraInfo: relayTime 1 =  " + settingInstance.get("relay-times", "继电器延时时间"));
////            ShellHelper.reboot();
//            Thread.sleep(5000);
//            outputProvider.reboot(OutputInterface.Output.RST);
        } catch (Exception e) {
            jsonResult = MessageConverter.uploadReceiveResult(context,
                    BestConstant.SERVICE_ID_COMMAND_CAMERA_INFORMATION, BestConstant.SET_CAMERA_INFORMATION_FAIL);
        }
        return jsonResult;
    }

    private void deleteAllTables(){
        //for (ORM orm : ORM_SET) {
        //    orm.deleteTable(DATABASE_ID);
        //}
    }

    private void createAllTables() {
        //for (ORM orm : ORM_SET) {
        //    orm.createTable(DATABASE_ID);
        //}
    }

    //private List<? extends ORM> getLogsByDate(ORM orm, Date startTime, Date endTime) throws SQLException {
    //    return orm.getDao(DATABASE_ID).queryBuilder().where().
    //            gt(TIMESTAMP, startTime).and().
    //            lt(TIMESTAMP, endTime).query();
    //}

    private void removeLogByMid(string mid, bool isSucceed) {
        if (isSucceed) {
            settingInstance.Remove(mid);
        }
    }

    private bool checkNullOrEmpty(string value) {
        return value != null && !string.IsNullOrEmpty(value);
    }

    public static bool checkPersonDatabaseHasData(){
        return false;
    }

    public static void clearPerson() {
        //new Person().clearTable(DATABASE_ID);
        //new PersonGroup().clearTable(DATABASE_ID);
        //new AccessControl().clearTable(DATABASE_ID);
        //new PersonBiometric().clearTable(DATABASE_ID);
        //new PersonExtra().clearTable(DATABASE_ID);

    }

}
}
